<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    use HasFactory;

    const TYPE = [
        '工程信息推送' => 0,
        '收藏信息' => 1,
    ];

    protected $table = 'messages';
    protected $primaryKey = 'id';
    public $timestamps = true;
    protected $guarded = [];

    public function sendUser()
    {
        return $this->belongsTo(User::class, 'send_user_id', 'id');
    }

    public function receiveUser()
    {
        return $this->belongsTo(User::class, 'receive_user_id', 'id');
    }

    public function content()
    {
        return $this->belongsTo(Content::class, 'content_id', 'id');
    }

    public function userReadMessages()
    {
        return $this->hasMany(UserReadMessage::class, 'message_id', 'id');
    }

    public function getTypeStrAttribute()
    {
        return array_search($this->type, self::TYPE);
    }

    public function getIsReadedAttribute()
    {
        $userId = app('userId');
        if ($userId) {
            return $this->userReadMessages->pluck('user_id')->search($userId) !== false;
        }
        return false;
    }
}
